<?php
//
//	file: includes/acp/acp_attach_ext_groups.php
//	author: ptirhiik
//	begin: 01/03/2006
//	version: 1.6.1 - 09/02/2007
//	license: http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
//
//	based on : attachment_mod copyright (c) 2002 Meik Sievertsen (acydburn)
//

if ( !defined('IN_PHPBB') )
{
	die('Hack attempt');
}

$cp_title = 'Manage_extension_groups';
$cp_title_explain = 'Manage_extension_groups_explain';

// we need some functions
include_once($config->url('includes/attach/class_attach_cp_fields'));

if ( !class_exists('forums') )
{
	include($config->url('includes/class_forums'));
}

class attach_manage_ext_groups extends form
{
	var $data;

	function attach_manage_ext_groups($requester, $parms='', &$fields)
	{
		$this->requester = $requester;
		$this->parms = empty($parms) ? array() : $parms;

		$this->data = array();
		parent::form($fields);
	}

	function process()
	{
		if ( $this->init() )
		{
			$this->check();
			$this->validate();
			$this->display();
			return true;
		}
		return false;
	}

	function init()
	{
		global $db;

		parent::init();
		$this->read();
		return true;
	}

	function read($force=false)
	{
		global $db, $config;

		// get extensions groups
		$this->data = array();
		$sql = 'SELECT *
					FROM ' . ATT_EXT_GROUPS_TABLE . '
					ORDER BY cat_id, ext_group_name, ext_group_id';
		$result = $db->sql_query($sql, false, __LINE__, __FILE__);
		while ( $row = $db->sql_fetchrow($result) )
		{
			$this->data[ intval($row['ext_group_id']) ] = $row;
		}
		$db->sql_freeresult($result);

		// get extensions
		$sql = 'SELECT ext_group_id, ext_id, extension
					FROM ' . ATT_EXTENSIONS_TABLE . '
					WHERE ext_group_id > 0
					ORDER BY ext_group_id, extension';
		$result = $db->sql_query($sql, false, __LINE__, __FILE__);
		while ( $row = $db->sql_fetchrow($result) )
		{
			$ext_group_id = intval($row['ext_group_id']);
			if ( isset($this->data[$ext_group_id]) )
			{
				if ( !isset($this->data[$ext_group_id]['extensions']) )
				{
					$this->data[$ext_group_id]['extensions'] = array(intval($row['ext_id']) => $row['extension']);
				}
				else
				{
					$this->data[$ext_group_id]['extensions'][ intval($row['ext_id']) ] = $row['extension'];
				}
			}
		}
		$db->sql_freeresult($result);

		// recache group/ext allowed
		if ( $force )
		{
			$config->globals['mod_attachment_CH']['extensions']->read(true);
		}
	}

	function check()
	{
		global $config, $db;
		global $error, $error_msg;
		global $warning, $warning_msg;

		if ( $error || $warning || !_button('add_new') )
		{
			return;
		}
		parent::check();
	}

	function validate()
	{
		global $config, $db, $forums;
		global $error, $error_msg;
		global $warning, $warning_msg;

		// forums auths actions
		$add_forum = $remove_forum = false;
		if ( ($ext_group_id = _read('gauth', TYPE_INT, 0, array(0 => '') + $this->data)) && !_button('close_window') && ($this->data[$ext_group_id]['cat_id'] != DENIED_CAT) )
		{
			$remove_forum = _button('remove_forum');
			$add_forum = _button('add_forum');

			if ( $remove_forum || $add_forum )
			{
				$forum_ids = $add_forum ? get_var('forum_ids', array(0)) : get_var('allowed_ids', array(0));
				if ( !empty($forum_ids) )
				{
					// moved ids
					$forum_ids = empty($forum_ids) ? array() : (in_array(-1, $forum_ids) ? array(-1 => true) : array_flip($forum_ids));

					// current value
					$res = !intval($this->data[$ext_group_id]['allow_group']) ? array() : (trim($this->data[$ext_group_id]['forum_permissions']) == '' ? array(-1) : $config->globals['mod_attachment_CH']['extensions']->decode($this->data[$ext_group_id]['forum_permissions']));
					$res = empty($res) ? array() : array_flip($res);

					// addition asked
					if ( $add_forum )
					{
						if ( in_array(-1, $forum_ids) )
						{
							$res = array(-1 => true);
						}
						else
						{
							if ( $forums === false )
							{
								if ( !class_exists('forums') )
								{
									include($config->url('includes/class_forums'));
								}
								$forums = new forums();
								$forums->read();
							}
							$selected_ids = array();
							if ( !empty($forums->data) )
							{
								foreach ( $forums->data as $forum_id => $data )
								{
									if ( (isset($res[$forum_id]) || isset($forum_ids[$forum_id])) && ($forums->data[$forum_id]['forum_type'] == POST_FORUM_URL) )
									{
										$selected_ids[ intval($forum_id) ] = true;
									}
								}
							}
							$res = $selected_ids;
							unset($selected_ids);
						}
					}
					else if ( $remove_forum )
					{
						if ( $forums === false )
						{
							if ( !class_exists('forums') )
							{
								include($config->url('includes/class_forums'));
							}
							$forums = new forums();
							$forums->read();
						}
						$selected_ids = array();
						if ( !empty($forums->data) )
						{
							foreach ( $forums->data as $forum_id => $data )
							{
								if ( (isset($res[$forum_id]) && !isset($forum_ids[$forum_id])) && ($forums->data[$forum_id]['forum_type'] == POST_FORUM_URL) )
								{
									$selected_ids[ intval($forum_id) ] = true;
								}
							}
						}
						$res = $selected_ids;
						unset($selected_ids);
					}
					unset($forum_ids);

					$fields = array();
					if ( empty($res) )
					{
						$fields = array(
							'forum_permissions' => '',
							'allow_group' => 0,
						);
					}
					else if ( isset($res[-1]) )
					{
						$fields = array(
							'forum_permissions' => '',
							'allow_group' => 1,
						);
					}
					else
					{
						krsort($res);
						$fields = array(
							'forum_permissions' => $config->globals['mod_attachment_CH']['extensions']->encode(array_keys($res)),
							'allow_group' => 1,
						);
					}
					$this->data[$ext_group_id] = array_merge($this->data[$ext_group_id], $fields);
					$sql = 'UPDATE ' . ATT_EXT_GROUPS_TABLE . '
								SET ' . $db->sql_fields('update', $fields) . '
								WHERE ext_group_id = ' . intval($ext_group_id);
					$db->sql_query($sql, false, __LINE__, __FILE__);
				}
				return;
			}
		}

		$deleted_id = _read('delete', TYPE_INT, 0, array(0 => '') + $this->data);
		if ( $error || $warning || (!_button('add_new') && !_button('edit_details') && !$deleted_id) )
		{
			return;
		}

		// process actions
		$deleted = $updated = $created = false;
		if ( $deleted_id )
		{
			$sql = 'DELETE FROM ' . ATT_EXT_GROUPS_TABLE . '
						WHERE ext_group_id = ' . intval($deleted_id);
			$db->sql_query($sql, false, __LINE__, __FILE__);
			unset($this->data[$deleted_id]);

			$sql = 'UPDATE ' . ATT_EXTENSIONS_TABLE . '
						SET ext_group_id = 0
						WHERE ext_group_id = ' . intval($deleted_id);
			$db->sql_query($sql, false, __LINE__, __FILE__);
			$deleted = true;
		}
		else if ( _button('edit_details') )
		{
			$ext_group_ids = get_var('group_ids', array(0));
			if ( !empty($ext_group_ids)  && !empty($this->data) )
			{
				$ext_group_ids = empty($ext_group_ids) ? array() : array_flip($ext_group_ids);
				$group_names = get_var('group_names', array(''));
				$cat_ids = get_var('cat_ids', array(0));
				$allow_groups = get_var('allow_groups', array(0));
				$download_modes = get_var('download_modes', array(0));
				$upload_icons = get_var('upload_icons', array(''));
				$max_filesize_values = get_var('max_filesize_values', array(0));
				$max_filesize_units = get_var('max_filesize_units', array(0));
				foreach ( $this->data as $ext_group_id => $data )
				{
					if ( isset($ext_group_ids[$ext_group_id]) )
					{
						$idx = $ext_group_ids[$ext_group_id];
						$fields = array(
							'ext_group_name' => trim(htmlspecialchars(stripslashes($group_names[$idx]))),
							'cat_id' => intval($cat_ids[$idx]),
							'allow_group' => (intval($cat_ids[$idx]) == DENIED_CAT) || !intval($allow_groups[$idx]) ? 0 : 1,
							'download_mode' => intval($download_modes[$idx]),
							'upload_icon' => trim(htmlspecialchars(stripslashes($upload_icons[$idx]))),
							'max_filesize' => intval($max_filesize_values[$idx]) * intval($max_filesize_units[$idx]),
						);
						if ( intval($cat_ids[$idx]) == DENIED_CAT )
						{
							$fields = array_merge($fields, array(
								'allow_group' => 0,
								'forum_permissions' => '',
							));
						}
						foreach ( $fields as $field_name => $value )
						{
							if ( $this->data[$ext_group_id][$field_name] == $value )
							{
								unset($fields[$field_name]);
							}
							else
							{
								$this->data[$ext_group_id][$field_name] = $value;
							}
						}
						if ( !empty($fields) )
						{
							$updated = true;
							$sql = 'UPDATE ' . ATT_EXT_GROUPS_TABLE . '
										SET ' . $db->sql_fields('update', $fields) . '
										WHERE ext_group_id = ' . intval($ext_group_id);
							$db->sql_query($sql, false, __LINE__, __FILE__);
						}
					}
				}
			}
		}
		else if ( _button('add_new') )
		{
			$fields = array(
				'ext_group_name' => trim($this->fields['ext_group_name']->value),
				'cat_id' => intval($this->fields['cat_id']->value),
				'allow_group' => (intval($this->fields['cat_id']->value) == DENIED_CAT) || !intval($this->fields['allow_group']->value) ? 0 : 1,
				'download_mode' => intval($this->fields['download_mode']->value),
				'upload_icon' => trim($this->fields['upload_icon']->value),
				'max_filesize' => intval($this->fields['max_filesize']->value),
				'forum_permissions'	=> '',
			);
			if ( !empty($fields['ext_group_name']) )
			{
				// check if already exists
				$sql = 'SELECT ext_group_id
							FROM ' . ATT_EXT_GROUPS_TABLE . '
							WHERE LOWER(ext_group_name) = \'' . $db->sql_escape_string(strtolower($fields['ext_group_name'])) . '\'
							LIMIT 1';
				$result = $db->sql_query($sql, false, __LINE__, __FILE__);
				$found = $db->sql_numrows($result);
				$db->sql_freeresult($result);
				if ( !$found )
				{
					$sql = 'INSERT INTO ' . ATT_EXT_GROUPS_TABLE . '
								(' . $db->sql_fields('fields', $fields) . ') VALUES(' . $db->sql_fields('values', $fields) . ')';
					$db->sql_query($sql, false, __LINE__, __FILE__);
					$created = true;
				}
			}
		}
		if ( $deleted || $updated || $created )
		{
			$this->read(true);
			$return_msg = $created ? 'Extension_group_added' : ($deleted ? 'Extension_group_deleted' : 'Extension_group_updated');
			message_return($return_msg, 'Click_return_attach_config', $config->url($this->requester, $this->parms, true));
		}
	}

	function display()
	{
		global $template, $config, $user, $forums;

		// upper form
		$this->buttons = array(
			'add_new' => array('txt' => 'Add_new', 'img' => 'cmd_add', 'key' => 'cmd_add'),
		);
		parent::display('ADD_FORM');

		// list
		if ( !empty($this->data) )
		{
			$categories = get_special_categories();
			$download_modes = get_download_modes();

			$color = false;
			$i = 0;
			foreach ( $this->data as $ext_group_id => $row )
			{
				$color = !$color;
				$units = array();
				$unit = size_get_units(intval($row['max_filesize']), $units);
				$template->assign_block_vars('row', array(
					'ROW_NUMBER' => $i,
					'GROUP_ID' => $ext_group_id,
					'GROUP_NAME' => _html_entities_encode($row['ext_group_name']),
					'ALLOW_GROUP' => intval($row['cat_id']) == DENIED_CAT ? 0 : intval($row['allow_group']),
					'DOWNLOAD_MODE' => intval($row['download_mode']),
					'UPLOAD_ICON' => _html_entities_encode($row['upload_icon']),
					'MAX_FILESIZE_VALUE' => round(intval($row['max_filesize']) / $unit),
					'MAX_FILESIZE_UNIT' => $unit,

					'U_GROUP_AUTH' => $config->url($this->requester, $this->parms + array('gauth' => $ext_group_id), true),
					'U_DELETE' => $config->url($this->requester, $this->parms + array('delete' => $ext_group_id), true),
				));
				$i++;
				$template->set_switch('row.disabled', intval($row['cat_id']) == DENIED_CAT);
				$template->set_switch('row.allow_group_checked', intval($row['allow_group']) && (intval($row['cat_id']) != DENIED_CAT));
				$template->set_switch('row.light', $color);

				// build lists
				$this->build_list('row.cat_opt', $categories, intval($row['cat_id']));
				$this->build_list('row.download_opt', $download_modes, intval($row['download_mode']));
				$this->build_list('row.unit_opt', $units, $unit);

				// display list of extensions
				if ( !empty($row['extensions']) )
				{
					$first = true;
					foreach ( $row['extensions'] as $ext_id => $extension )
					{
						$template->assign_block_vars('row.extension', array(
							'EXTENSION' => $extension,
						));
						$template->set_switch('row.extension.first', $first);
						$first = false;
					}
				}
				else
				{
					$template->assign_block_vars('row.extension', array(
						'EXTENSION' => $user->lang('None'),
					));
					$template->set_switch('row.extension.first', true);
				}
			}
		}
		$template->assign_vars(array(
			'L_GROUP' => $user->lang('Extension_group'),
			'L_CATEGORY' => $user->lang('Special_category'),
			'L_EXTENSIONS' => $user->lang('Extensions'),
			'L_ATTRIBUTS' => $user->lang('Extension_groups_attributs'),
			'L_DOWNLOAD_MODE' => $user->lang('Download_mode'),
			'L_UPLOAD_ICON' => $user->lang('Upload_icon'),
			'L_MAX_FILESIZE' => $user->lang('Max_groups_filesize'),

			'L_ALLOWED' => $user->lang('Allowed'),
			'L_ACTION' => $user->lang('Action'),
			'L_NO_GROUPS' => $user->lang('No_extension_groups'),

			'I_GROUP_AUTH' => $user->img('cmd_select'),
			'L_GROUP_AUTH' => $user->lang('Allowed_forums'),
			'I_DELETE' => $user->img('cmd_delete'),
			'L_DELETE' => $user->lang('Delete'),
		));
		$template->set_switch('details');

		// forums auths
		if ( ($ext_group_id = _read('gauth', TYPE_INT, 0, array(0 => '') + $this->data)) && !_button('close_window') && ($this->data[$ext_group_id]['cat_id'] != DENIED_CAT) )
		{
			_hide('gauth', $ext_group_id);

			// get forums already set
			$forum_ids = !intval($this->data[$ext_group_id]['allow_group']) ? array() : (trim($this->data[$ext_group_id]['forum_permissions']) == '' ? array(-1) : $config->globals['mod_attachment_CH']['extensions']->decode($this->data[$ext_group_id]['forum_permissions']));

			// send to template
			$template->assign_block_vars('auths', array(
				'L_CATEGORY' => sprintf($user->lang('Group_permissions_title'), trim($this->data[$ext_group_id]['ext_group_name'])),
				'L_CATEGORY_EXPLAIN' => $user->lang('Group_permissions_explain'),
				'L_ALLOWED_FORUMS' => $user->lang('Allowed_forums'),
				'L_ADD_FORUMS' => $user->lang('Add_forums'),

				'I_REMOVE_FORUM' => $user->img('cmd_delete'),
				'L_REMOVE_FORUM' => $user->lang('Remove_selected'),
				'I_ADD_FORUM' => $user->img('cmd_add'),
				'L_ADD_FORUM' => $user->lang('Add_selected'),
				'I_CLOSE_WINDOW' => $user->img('cmd_close'),
				'L_CLOSE_WINDOW' => $user->lang('Close_window'),
			));

			// display boxes
			if ( $forums === false )
			{
				if ( !class_exists('forums') )
				{
					include($config->url('includes/class_forums'));
				}
				$forums = new forums();
				$forums->read();
			}
			$this->build_forums_list('auths.allowed', $forum_ids, '');
			$this->build_forums_list('auths.forum', '', $forum_ids, true);
		}

		// list
		display_buttons(array(
			'edit_details' => array('txt' => 'Edit', 'img' => 'cmd_edit', 'key' => 'cmd_edit'),
		), 'details');
		$template->assign_block_vars('cp_content', array('BOX' => $template->include_file('acp/acp_attach_ext_groups_box.tpl', 'row')));
	}

	function build_list($tpl_switch, &$list, $selected)
	{
		global $template, $user;
		foreach ($list as $key => $name )
		{
			$template->assign_block_vars($tpl_switch, array(
				'KEY' => $key,
				'NAME' => $user->lang($name),
			));
			$template->set_switch($tpl_switch . '.selected', $key == $selected);
		}
	}

	function build_forums_list($tpl_switch, $basics='', $excludes='', $all_forums=false)
	{
		global $template, $forums, $user;

		$basics = array_flip($all_forums ? $forums->keys : (empty($basics) ? array() : (in_array(-1, $basics) ? array(-1) : $basics)));
		$excludes = empty($excludes) ? array() : array_flip($excludes);

		// first pass
		$res = array();
		$tres = array();
		for ( $i = count($forums->keys) - 1; $i >= 0; $i-- )
		{
			$forum_id = $forums->keys[$i];
			$is_active = isset($basics[$forum_id]) && !isset($excludes[$forum_id]) && ($forums->data[$forum_id]['forum_type'] == POST_FORUM_URL);
			if ( isset($tres[$forum_id]) )
			{
				$res[$forum_id] = array_merge($tres[$forum_id], array('is_active' => $is_active));
				unset($tres[$forum_id]);
			}
			else if ( $is_active )
			{
				$res[$forum_id] = array('is_active' => true, 'main_id' => intval($forums->data[$forum_id]['forum_main']), 'subs' => array(), 'last_child_id' => $forum_id);
			}

			// ensure the parents are there
			if ( isset($res[$forum_id]) && ($forum_id > 0) )
			{
				// store the ancester to the temporary array
				$main_id = intval($forums->data[$forum_id]['forum_main']);
				while ( !isset($tres[$main_id]) )
				{
					$tres[$main_id] = array('is_active' => false, 'main_id' => intval($forums->data[$main_id]['forum_main']), 'subs' => array(), 'last_child_id' => $main_id);
					if ( $main_id == 0 )
					{
						break;
					}
					$main_id = intval($forums->data[$main_id]['forum_main']);
				}

				// push to parent
				$main_id = intval($res[$forum_id]['main_id']);
				array_unshift($tres[$main_id]['subs'], $forum_id);
				if ( $tres[$main_id]['last_child_id'] == $main_id )
				{
					$tres[$main_id]['last_child_id'] = $res[$forum_id]['last_child_id'];
				}
			}
		}
		unset($tres);

		// prepare return
		$front_pic = isset($basics[-1]) || $all_forums ? array(-1 => array('is_active' => true, 'txt' => $user->lang('Perm_all_forums'))) + (empty($res) ? array() : array(-2 => array('is_active' => false, 'txt' => '--------------------------'))) : array();

		// restart from top and get levels & close
		if ( $count_keys = count($res) )
		{
			$keys = array_reverse(array_keys($res));
			$last_ids = $levels = array();
			for ( $i = 0; $i < $count_keys; $i++ )
			{
				$cur_id = $keys[$i];
				$last_ids[$cur_id] = $cur_id;
				$levels[$cur_id] = 0;
				if ( $i > 0 )
				{
					$last_ids[ $res[$cur_id]['main_id'] ] = $cur_id;
					$levels[$cur_id] = $levels[ $res[$cur_id]['main_id'] ] + 1;
				}
			}

			// now build the front
			$close = array();
			$previous_level = 0;
			foreach ( $last_ids as $cur_id => $last_child_id )
			{
				$close[ $levels[$cur_id] ] = empty($cur_id) || ($last_ids[ $res[$cur_id]['main_id'] ] == $cur_id);

				$linefeed = $option = '';
				for ( $i = 1; $i <= $levels[$cur_id]; $i++ )
				{
					if ( $i == $levels[$cur_id] )
					{
						$linefeed .= $user->lang('tree_pic_' . TREE_VSPACE);
						$option .= $user->lang('tree_pic_' . ($close[$i] ? TREE_CLOSE : TREE_CROSS));
					}
					else
					{
						$linefeed .= $user->lang('tree_pic_' . ($close[$i] ? TREE_HSPACE : TREE_VSPACE));
						$option .= $user->lang('tree_pic_' . ($close[$i] ? TREE_HSPACE : TREE_VSPACE));
					}
				}
				if ( $previous_level > $levels[$cur_id] )
				{
					$front_pic[ (LOWER_ID - count($front_pic)) ] = array('is_active' => false, 'txt' => $linefeed);
				}
				$front_pic[$cur_id] = array('is_active' => $res[$cur_id]['is_active'], 'txt' => $option . $user->lang($forums->data[$cur_id]['forum_name']));
				$previous_level = $levels[$cur_id];
			}
		}
		unset($res);

		// send to display
		if ( !empty($front_pic) )
		{
			$template->set_switch($tpl_switch);
			foreach ( $front_pic as $forum_id => $data )
			{
				$template->assign_block_vars($tpl_switch . '.opt', array(
					'FORUM_ID' => $forum_id,
					'FORUM_NAME' => $data['txt'],
				));
				$template->set_switch($tpl_switch . '.opt.disabled', !$data['is_active']);
			}
		}
	}
}

// adjust field
if ( isset($fields['max_filesize']) )
{
	$fields['max_filesize']['value'] = intval($config->globals['mod_attachment_CH']['config']->data['max_filesize']);
}

// process
$parms = array(
	'mode' => $menu_id,
	'sub' => $subm_id == $menu_id ? '' : $subm_id,
	'ctx' => $ctx_id == $subm_id ? '' : $ctx_id,
);
$form = new attach_manage_ext_groups($cp_requester, $cp_parms + $parms, $fields);
$form->process();
$template->set_filenames(array('body' => 'cp_generic.tpl'));

?>